// var amapFile  = require("amap-wx");
var countTooGetLocation = 0;
var total_micro_second = 0;
var starRun = 0;
var totalSecond = 0;
var oriMeters = 0.0;
const app = getApp();
var pauseName = 0;
var settimeout;
var point = [];
var miscrodis = 0;
var totaldistance = 0;
var latfirst, lonfirst, latnow, lonnow;
var countdistance = 0;
var leavetime = app.globalData.currenttime;
var tempdistance = 0;
var initloc = true; //初始坐标marker
var finished = app.globalData.finished;
var startRuntime;
/* 毫秒级倒计时 */
function count_down(that) {
  if (starRun == 0) {
    return;
  } else {
    var temptime = timeTosecond(leavetime);//数据秒
    if (temptime != 0) {
      total_micro_second = temptime;
      leavetime = "0:00:00";
    }
    var time = date_format(total_micro_second);
    var latfirst = latnow;
    var lonfirst = lonnow;
    if (countTooGetLocation >= 2000) { //1000为1s
      that.getLocation(false);
      var templine = that.data.polyline;
      //console.log(that.data.polyline);

      var test = templine.map(function (item) {
        return item.points[0];
      });
      var lattemp = parseFloat(test[0].latitude);
      var lontemp = parseFloat(test[0].longitude);
      //console.log("经度" + latfirst + "纬度" + lonfirst + "纬度" + latnow + "经度" + lonnow);
      miscrodis = getDistance(latfirst, lonfirst, lattemp, lontemp);
      countdistance += miscrodis;
      // console.log(countdistance+"多点");
      if (countdistance >= 10) {//大于10米
        totaldistance = +countdistance;
        countdistance = 0;
        var meters = parseFloat((totaldistance / 1000).toFixed(2));
        //var showMeters = meters.toFixed(2);
        that.setData({
          meters: meters
        })
        console.log(countdistance + "总共" + meters);
      }

      countTooGetLocation = 0;
    }

    //毫秒计时器
    settimeout = setTimeout(function () {
      countTooGetLocation += 1000;
      total_micro_second += 1000;
      count_down(that);
      that.updateTime(time);
    }, 1000
    )
  }

}

//设置地理位置
function settinglocation(status) {
  wx.showModal({
    title: '提示',
    content: '请在设置里选择"使用小程序期间和离开小程序后"，才能运行跑步功能',
    showCancel: true, //是否显示取消按钮-----》false去掉取消按钮
    cancelText: "否", //默认是“取消”
    cancelColor: 'skyblue', //取消文字的颜色
    confirmText: "设置", //默认是“确定”
    confirmColor: 'skyblue', //确定文字的颜色
    success: function (res) {
      if (res.cancel) {
        //点击取消
        wx.showToast({ title: '定位失败，请重试', icon: 'none' });
        console.log("取消授权");
        settinglocation(status);
      } else if (res.confirm) {
        //点击确定
        wx.openSetting({
          success(data) {
            if (data.authSetting["scope.userLocation"] == true) {
              wx.showToast({
                title: '授权成功',
                icon: 'success',
                duration: 2000,
                success() {
                  status = true;
                }
              })

            }
          }
        })

      }
    }
  })
}


// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;


  return hr + ":" + min + ":" + sec + " ";
}

function timeTosecond(params) {
  var timestr = params.split(":");
  var hr = Math.floor(parseInt(timestr[0]) * 3600);//时转秒
  var min = Math.floor(parseInt(timestr[1]) * 60);//分转秒
  var sec = Math.floor(parseInt(timestr[2]));
  var timesecond = hr + min + sec;
  return timesecond * 1000;
}


// function getDistance(lat1, lng1, lat2, lng2) { 
//     var dis = 0;
//     var radLat1 = toRadians(lat1);
//     var radLat2 = toRadians(lat2);
//     var deltaLat = radLat1 - radLat2;
//     var deltaLng = toRadians(lng1) - toRadians(lng2);
//     var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
//     return dis * 6378137;

//     function toRadians(d) {  return d * Math.PI / 180;}
// } 


function getDistance(latFrom, lngFrom, latTo, lngTo) {
  var rad = function (d) {//计算角度
    return parseFloat(d * Math.PI / 180.0);
  }
  // var radLatFrom = rad(parseFloat());
  var EARTH_RADIUS = 6378136.49;
  var radLatFrom = rad(latFrom);
  var radLatTo = rad(latTo);
  // console.log(radLatFrom + "经度" + radLatTo);
  var a = Math.abs(radLatFrom - radLatTo);
  var b = Math.abs(rad(lngFrom) - rad(lngTo));
  // console.log(a + "运算后" + b);
  var distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLatFrom) * Math.cos(radLatTo) * Math.pow(Math.sin(b / 2), 2)));
  distance = distance * EARTH_RADIUS;
  distance = Math.round(distance * 10000) / 10000;
  console.log(distance + "两点之间距离");
  return parseFloat(distance.toFixed(2));
}


function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

//****************************************************************************************
//****************************************************************************************

Page({
  data: {
    markers: [],
    meters: "0.00",
    time: "0:00:00",
    plan: app.globalData.plan,
    changeView2: 'display:none',
    changeView1: 'display:block',
    startTime: 0,
    endTime: 0,
    stopOrOn: "暂停跑步",
    latitude: 0,
    longitude: 0,
    markers: [],
    polyline: [],
  },
  //****************************
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // wx.startLocationUpdateBackground({
    //   success(res) {
    //    console.log('开启后台定位', res)
    //   },
    //   fail(res) {
    //    console.log('开启后台定位失败', res)
    //   }
    //  })
    //  var Oritime=options.time;//获取初始time
    //   var Orimeter=options.meters;
    //  console.log(Oritime);
    //监听location功能
    // getApp().setWatcher(this.data, this.watch);
    this.getLocation(initloc);
    this.setData({
      plan: app.globalData.plan,
    })
    //leavetime=Oritime;
    // var timesecond=this.data.time.split(":");
    // console.log(timesecond[2]+"当前时间");
    if (starRun == 1) {
      this.setData({
        changeView1: "display:none",
        changeView2: "display:block",
      })
    }
    if (pauseName == 1) {
      this.setData({
        changeView1: "display:none",
        changeView2: "display:block",
        stopOrOn: "继续",
        time: leavetime,
        meters: tempdistance,
      })
      pauseName = 0;
    }
    count_down(this);
  },
  onShow: function (options) {
    var that = this;
    //app.globalData.livelocation=false;
    wx.getSetting({
      success(res) {// 查看所有权限
        let status = res.authSetting['scope.userLocation'];
        if (!status) {
          //弹出设置location
          settinglocation();
        }
      }
    })
  },
  //离开页面
  onUnload: function () {
    var time = this.data.time;
    var count = this.data.meters;
    total_micro_second = 0;
    countTooGetLocation = 0;
    clearTimeout(settimeout);//清除不必要的时间
    //存入全局变量
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];   //当前页面
    var prevPage = pages[pages.length - 2];  //上一个页面
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    
    prevPage.setData({
      time: time,
      meters: count
    })
    leavetime = time;
    tempdistance = count;
    app.globalData.currenttime = time;
    app.globalData.finished = count;
    this.setData({
      meters: count,
      time: time
    })
  },



  //****************************
  starRun: function () {
    //查看是否打开了地理位置
    var that = this;
    var startime = new Date();
    startRuntime = startime;
    function openrun(status) {
      if (status) {
        that.setData({
          changeView1: "display:none",
          changeView2: "display:block"
        })
        starRun = 1;
        if (starRun == 0) {
          return;
        }
        count_down(that);
      }
    }
    wx.getSetting({
      success(res) {// 查看所有权限
        let status = res.authSetting['scope.userLocation']// 查看位置权限的状态，此处为初次请求，所以值为undefined
        if (!status) {// 如果是首次授权(undefined)或者之前拒绝授权(false)
          wx.authorize({ // 发起请求用户授权
            scope: 'scope.userLocation',
            success() {// 用户允许了授权
              status = true;
              console.log("授权成功");
              settinglocation(status);
              openrun(status);
            },
            fail() {
              console.log("授权失败");
              wx.showToast({ title: '定位失败2，请重试', icon: 'none' });
              status = true;
              settinglocation(status);
            }
          })
        } else {
          status = true;
          openrun(status);
        }
      },
    },
    )
    // this.timer = setInterval(repeat, 1000);
    //     function repeat() {
    //         that.getLocation();
    //         //that.drawline();
    //         console.log('re');
    //     }

  },


  //****************************
  stopRun: function () {
    var stopOrOn = "";
    if (pauseName == 1) {
      stopOrOn = "暂停跑步";
      starRun = 1;
      pauseName = 0;
    } else {
      stopOrOn = "继续";
      starRun = 0;
      pauseName = 1;
    }
    this.setData({
      stopOrOn: stopOrOn
    })
    count_down(this);
    finished += this.data.meters;
    app.globalData.task = finished;
  },

  handleTouchStart: function (e) {
    this.startTime = e.timeStamp;
    console.log( this.startTime +"开始")

  },



  //touch end

  bindtap: function (e) {
    var that = this;
    var touchstartime = that.startTime;
    var touchendtime=e.timeStamp;
    var startime = startRuntime;//按钮点击得标准时间
    var endtime = new Date();
    var meters = that.data.meters;
    var time=this.data.time;
   if(touchendtime-touchstartime>100){
      //长按操作 调用结束录像方法
      starRun = 0;
      this.setData({
        changeView1: "display:block",
        changeView2: "display:none",
        time: "0:00:00",
        meters: "0.00"
      })
      count_down(this);
      console.log("长按生效");
      total_micro_second = 0;
      countTooGetLocation = 0;
      clearTimeout(settimeout);
    }
    wx.getUserInfo({
      success: function (res) {
        var useinfo = res.userInfo.nickName;
        if (res.userInfo.nickName) {
          wx.showModal({
            title: '提示',
            content: '是否保存此次运动记录',
            showCancel: true, //是否显示取消按钮-----》false去掉取消按钮
            cancelText: "否", //默认是“取消”
            cancelColor: 'skyblue', //取消文字的颜色
            confirmText: "确定", //默认是“确定”
            confirmColor: 'skyblue', //确定文字的颜色
            success: function (res) {
              // startime= new Date(startime).format("yyyy-MM-dd hh:mm:ss");
              // endtime=new Date(endtime).format("yyyy-MM-dd hh:mm:ss");
             
              var rundatalist = creatdatalist(startime, endtime, app.globalData.plan, meters, time, useinfo);
              console.log(rundatalist);
              var rundata = wx.getStorageSync('datalist') || [];
              if (rundata[29] != undefined) {
                rundata.shift();//删除最后一个
                console.log(rundata.length+"chang");
              }
              rundata.push(rundatalist);
              console.log(rundata.length+"chang");
            //  var promise=new promise(function(){
              wx.setStorageSync('datalist', rundata)
      
            //  promise.then(res=>{
              var page = getCurrentPages().pop();  
              if (page == undefined || page == null) return;  
              page.onLoad();  
           
            }
          })
        }
      }
    })

  },


  handleTouchEnd: function(e) {   
    //console.log("endTime - startTime = "  +  (this.endTime  -  this.startTime));
    //console.log(new Date(e.timeStamp) +"时间");
    this.endTime  =  e.timeStamp;   
    console.log(new Date(this.endTime*1000)+"endtime")
  },


  //****************************
  updateTime: function (time) {
    this.setData({
      time: time,
    })

  },

  //时间格式


  //取得定位
  // getlocation:function(){
  //   var that = this;
  //   //var key = config.Config.key;
  //   var myAmapFun = new amapFile.AMapWX({key: '963cf3142b8f650d6b1a53f6a30e6480'});
  //   myAmapFun.getRegeo({
  //     success: (res) => {
  //       console.log(res, res[0].regeocodeData.addressComponent.city,"hah")//获取城市
  //     }
  //   })
  //   myAmapFun.getWalkingRoute({
  //     origin: '116.481028,39.989643',
  //     destination: '116.434446,39.90816',
  //     success: function(data){
  //       var points = [];
  //       if(data.paths && data.paths[0] && data.paths[0].steps){
  //         var steps = data.paths[0].steps;
  //         for(var i = 0; i < steps.length; i++){
  //           var poLen = steps[i].polyline.split(';');
  //           for(var j = 0;j < poLen.length; j++){
  //             points.push({
  //               longitude: parseFloat(poLen[j].split(',')[0]),
  //               latitude: parseFloat(poLen[j].split(',')[1])
  //             })
  //           } 
  //         }
  //       }
  //       that.setData({
  //         polyline: [{
  //           points: points,
  //           color: "#0091ff",
  //           width: 6
  //         }]
  //       });
  //       if(data.paths[0] && data.paths[0].distance){
  //         that.setData({
  //           distance: data.paths[0].distance + '米'
  //         });
  //       }
  //       if(data.paths[0] && data.paths[0].duration){
  //         that.setData({
  //           cost: parseInt(data.paths[0].duration/60) + '分钟'
  //         });
  //       }
  //     },
  //     fail: function(info){
  //       console.log(info)
  //     }
  //   })

  // },
  //****************************
  getLocation: function (initloc) {
    var that = this;
    var lat, lon;
    //var key = config.Config.key;
    // var myAmapFun = new amapFile.AMapWX({key: '963cf3142b8f650d6b1a53f6a30e6480'});
    wx.getLocation({
      type: 'gcj02',
      success: (data) => {
        lat = data.latitude;
        lon = data.longitude;
        that.setData({
          latitude: lat,
          longitude: lon,
        });
        if (initloc) {
          that.setData({
            latitude: lat,
            longitude: lon,
            markers: [{
              id: 0
              , iconPath: "../../resources/mylocation.png"
              , longitude: lon
              , latitude: lat
              , width: 30
              , height: 30
            }]
          });
        }
        point.push({ latitude: lat, longitude: lon });
        latnow = lat;
        lonnow = lon;
        this.setData({
          polyline: [{
            points: point,
            color: '#ff7700',
            width: 4,
            dottedLine: true
          }]
        });
      },
      fail(res) {
        wx.showToast({ title: '定位失败，请重试', icon: 'none' })
      }
    })



  },

  Rad: function (d) {
    return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
  },

  //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
  //  GetDistance: function (lat1,lng1,lat2,lng2){

  //      var radLat1 = this.Rad(lat1);
  //      var radLat2 = this.Rad(lat2);
  //      var a = radLat1 - radLat2;
  //      var  b = this.Rad(lng1) - this.Rad(lng2);
  //      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
  //      Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
  //      s = s *6378.137 ;// EARTH_RADIUS;
  //      s = Math.round(s * 10000) / 10000; //输出为公里
  //      //s=s.toFixed(2);
  //      return s;
  //  },

  //  getFlatternDistance:  function(lat1,lng1,lat2,lng2){
  //   var f = getRad((lat1 + lat2)/2);
  //   var g = getRad((lat1 - lat2)/2);
  //   var l = getRad((lng1 - lng2)/2);

  //   var sg = Math.sin(g);
  //   var sl = Math.sin(l);
  //   var sf = Math.sin(f);

  //   var s,c,w,r,d,h1,h2;
  //   var a = EARTH_RADIUS;
  //   var fl = 1/298.257;

  //   sg = sg*sg;
  //   sl = sl*sl;
  //   sf = sf*sf;

  //   s = sg*(1-sl) + (1-sf)*sl;
  //   c = (1-sg)*(1-sl) + sf*sl;

  //   w = Math.atan(Math.sqrt(s/c));
  //   r = Math.sqrt(s*c)/w;
  //   d = 2*w*a;
  //   h1 = (3*r -1)/2/c;
  //   h2 = (3*r +1)/2/s;

  //   return d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
  // },
  //   getLngLat: function(){
  //     var that = this;
  //     this.mapCtx = wx.createMapContext("map4select");
  //     this.mapCtx.getCenterLocation({
  //       success: function(res){

  //           that.setData({
  //           longitude: res.longitude
  //           ,latitude: res.latitude
  //           ,markers:[
  //             {
  //             id: 0
  //             ,iconPath: "../../resources/locationcenter.png"
  //             ,longitude: res.longitude
  //             ,latitude: res.latitude
  //             ,width: 30
  //             ,height: 30
  //             }
  //           ]
  //         })

  //       }
  //     })
  // },
  // regionchange(e) {
  //   // 地图发生变化的时候，获取中间点，也就是用户选择的位置
  //     if(e.type == 'end'){
  //         this.getLngLat()
  //     }
  // },


  // showMarkerInfo: function(data,i){
  //   this.setData({
  //     textData: {
  //       name: data[i].name,
  //       desc: data[i].address
  //     }
  //   });
  // },
  //  drawline :function() {
  //    console.log("ok"+point);
  //    var les=[{latitude:"31.228603",longitude:"121.688337"},{latitude:"31.228603",longitude:"122.688337"},{latitude:"31.228603",longitude:"123.688337"},{latitude:"31.228603",longitude:"124.688337"},{latitude:"31.228603",longitude:"125.688337"}];

  // }

})
//构建数据格式
function creatdatalist(startTime, endTime, aimmeters, finishedmeter, time, username) {//分别为运动开始时间，结束时间，里程，花费时间，用户名
  var weekday = endTime.getDay();
  //startTime= new Date(startTime).format("yyyy-MM-dd hh:mm:ss");
  //endTime=new Date(endTime).format("yyyy-MM-dd hh:mm:ss");
  console.log(time+"time")
  var week=[
    {id:1,name:"一"},
    {id:2,name:"二"},
    {id:3,name:"三"},
    {id:4,name:"四"},
    {id:5,name:"五"},
    {id:6,name:"六"},
    {id:7,name:"七"},
  ]
  var weekname="";
    week.map(function(item,index,week){
      if(item.id===weekday){
        weekname=item.name
      }
    })
//转化周
  var  arr=time.split(":")//持续时间
  time=parseInt(arr[0])*3600+parseInt(arr[1])*60+parseInt(arr[2]);
  if(time<60){
    time=time+"s"
  }else{
    time=parseInt(time/60)+"min"
  }
  var rundatalist = {
    startTime: startTime,
    endTime: endTime,
    aimmeters: aimmeters,
    finishedmeter: finishedmeter,
    time: time,
    weekday: weekname,
    username: username
  }
  return rundatalist;
};
Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份 
    "d+": this.getDate(),                    //日 
    "h+": this.getHours(),                   //小时 
    "m+": this.getMinutes(),                 //分 
    "s+": this.getSeconds(),                 //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds()             //毫秒 
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}
function time_format(time) {
  // 判断时间戳是否为13位数，如果不是则*1000，时间戳只有13位数(带毫秒)和10(不带毫秒)位数的
  if(time.toString().length == 13){
    var tme = getDate(time);
  }else{
    var tme = getDate(time * 1000);
  }
  var Y = tme.getFullYear();
  var M = (tme.getMonth() + 1 < 10 ? '0' + (tme.getMonth() + 1) : tme.getMonth() + 1);
  var D = tme.getDate();
  var h = tme.getHours();
  var m = tme.getMinutes();
  var s = tme.getSeconds();
  tem1 = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
  return tem1;
}